package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    /**
     * 自媒体文章审核
     *
     * @param id
     */
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章 并判断是否为空
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            //等于null抛出异常
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //待审核状态
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从内容中提取纯文本内容和图片
            Map<String, Object> textAndImages = handleTextAndImages(wmNews);
            //2.审核文本内容，阿里云接口
            boolean isTextScan = handleTextScan((String) textAndImages.get("content"), wmNews);
            //3.审核图片。。阿里云接口
            boolean isImageSacn = handImageScan((List<String>) textAndImages.get("images"),wmNews);
            if(!isImageSacn)return;
        }
    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;
    private boolean handImageScan(List<String> images, WmNews wmNews)  {
        //下载图片到minio中
        //进行图片去重
        boolean flage=true;
        if (images==null ||images.size()==0){
            return  flage;
        }

         images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>();
        for (String image : images) {
            //上传
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }
        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map!=null){
                if (map.get("suggestion").equals("block")) {
                    flage = false;
                    updateWmNews(wmNews, 2, "当前文章中存在违规信息");
                }
                if (map.get("suggestion").equals("review")) {
//人工审核
                    flage = false;
                    updateWmNews(wmNews, 3, "当前文章中存在 不确定内容");
                }
            }
            //转人工
        } catch (Exception e) {
            flage=false;
            e.printStackTrace();
        }
        return flage;
    }

    /**
     * 审核文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    //阿里云接口
    @Autowired
    private GreenTextScan greenTextScan;


    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flage = true;
        if ((wmNews.getTitle() + "_" + content).length() == 0) {
            return flage;
        }
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null) {
//审核状态，，，审核失败
                if (map.get("suggestion").equals("block")) {
                    flage = false;
                    updateWmNews(wmNews, 2, "当前文章中存在违规信息");
                }
                if (map.get("suggestion").equals("review")) {
//人工审核
                    flage = false;
                    updateWmNews(wmNews, 3, "当前文章中存在 不确定内容");
                }
            }
        } catch (Exception e) {
            flage = false;
            e.printStackTrace();
        }


        return false;
    }

    /**
     * 修改文章内容
     *
     * @param wmNews
     * @param ststus
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, int ststus, String reason) {
        wmNews.setStatus((short) ststus);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从自媒体的内容中提取文本和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文本内容
        StringBuilder stringBuilder = new StringBuilder();
        //图片内容
        ArrayList<String> images = new ArrayList<>();
        //提取文本和内容
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            //获取里面的文本内容信息
            List<Map> map = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map maps : map) {
                if (maps.get("type").equals("text")) {
                    stringBuilder.append(maps.get("value"));
                }
                //获取图片
                if (maps.get("type").equals("image")) {
                    images.add((String) maps.get("value"));
                }
            }
        }
        //提取图片封面 用逗号分割 默认第一张
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            //进行分割
            String[] split = wmNews.getImages().split(",");
//保存
            images.addAll(Arrays.asList(split));
        }
//返回
        Map<String, Object> map = new HashMap<>();
        map.put("content", stringBuilder.toString());
        map.put("images", images);
        return map;
    }
}
